package com.qiandao.xuexitong.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiandao.xuexitong.common.PageResult;
import com.qiandao.xuexitong.common.Result;
import com.qiandao.xuexitong.dto.*;
import com.qiandao.xuexitong.entity.AttendanceTask;
import com.qiandao.xuexitong.entity.Classroom;
import com.qiandao.xuexitong.exception.BusinessException;
import com.qiandao.xuexitong.service.AttendanceTaskService;
import com.qiandao.xuexitong.service.ClassroomService;
import com.qiandao.xuexitong.util.UserContext;

import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URLEncoder;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 教师端控制器
 */
@RestController
@RequestMapping("/api/teacher")
@RequiredArgsConstructor
public class TeacherController {
    
    private final ClassroomService classroomService;
    private final AttendanceTaskService attendanceTaskService;
    
    private static final Logger log = LoggerFactory.getLogger(TeacherController.class);
    
    /**
     * 创建班级
     */
    @PostMapping("/classroom")
    public Result<Void> createClassroom(@Validated @RequestBody ClassroomListDTO dto) {
        Long teacherId = UserContext.getUserId();
        classroomService.createClassroom(teacherId, dto.getName(),dto.getCode());
        return Result.success();
    }
    
    /**
     * 获取我的班级列表
     */
    @GetMapping("/classroom/list")
    public Result<Page<ClassroomListDTO>> getClassroomList(Page<ClassroomListDTO> page) {
        Long teacherId = UserContext.getUserId();
        Page<ClassroomListDTO> result = (Page<ClassroomListDTO>) classroomService.getClassroomList(teacherId,page);
        return Result.success(result);
    }
    
    /**
     * 添加学生到班级
     */
    @PostMapping("/classroom/{classroomId}/student/{studentId}")
    public Result<Void> addStudentToClassroom(@PathVariable Long classroomId, @PathVariable List<Long> studentId) {
        Long teacherId = UserContext.getUserId();
        classroomService.addStudentsToClassroom(teacherId, classroomId, studentId);
        return Result.success();
    }
    
    /**
     * 发起签到任务
     */
    @PostMapping("/attendance-task")
    public Result createAttendanceTask(@Valid @RequestBody CreateAttendanceTaskDTO dto) {
        // 从ThreadLocal中获取教师ID
        Long teacherId = UserContext.getUserId();
        
        // 创建签到任务
        classroomService.createAttendanceTask(teacherId, dto);
        
        return Result.success("创建成功");
    }
    
    /**
     * 创建二维码签到任务
     */
    @PostMapping("/attendance/qrcode")
    public Result<QrCodeInfoDTO> createQrCodeAttendanceTask(@Validated @RequestBody CreateQrCodeAttendanceTaskDTO dto) {
        Long teacherId = UserContext.getUserId();
        QrCodeInfoDTO qrCodeInfo = attendanceTaskService.createQrCodeAttendanceTask(teacherId, dto);
        return Result.success(qrCodeInfo);
    }
    
    @PostMapping("/attendance/gesture")
    public Result<Void> createGestureAttendanceTask(@Validated @RequestBody CreateGestureAttendanceTaskDTO dto) {
        Long teacherId = UserContext.getUserId();
        attendanceTaskService.createGestureAttendanceTask(teacherId, dto);
        return Result.success();
    }
    
    @PostMapping("/attendance/location")
    public Result<Void> createLocationAttendanceTask(@Validated @RequestBody CreateLocationAttendanceTaskDTO dto) {
        Long teacherId = UserContext.getUserId();
        attendanceTaskService.createLocationAttendanceTask(teacherId, dto);
        return Result.success();
    }
    
    @PostMapping("/attendance/code")
    public Result<Void> createCodeAttendanceTask(@Validated @RequestBody CreateCodeAttendanceTaskDTO dto) {
        Long teacherId = UserContext.getUserId();
        attendanceTaskService.createCodeAttendanceTask(teacherId, dto);
        return Result.success();
    }
    
    @PostMapping("/attendance/quick")
    public Result<Void> createQuickAttendanceTask(@Validated @RequestBody CreateQuickAttendanceTaskDTO dto) {
        Long teacherId = UserContext.getUserId();
        attendanceTaskService.createQuickAttendanceTask(teacherId, dto);
        return Result.success();
    }
    
    /**
     * 查询教师签到任务列表
     */
    @GetMapping("/attendance/tasks")
    public Result<PageResult<AttendanceTaskListDTO>> getAttendanceTasks(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size) {
        Long teacherId = UserContext.getUserId();
        Page<AttendanceTask> page = new Page<>(current, size);
        IPage<AttendanceTaskListDTO> result = attendanceTaskService.getTeacherAttendanceTasks(teacherId, page);
        return Result.success(PageResult.success(result));
    }
    
    /**
     * 获取签到任务详情
     */
    @GetMapping("/attendance/task/{taskId}/detail")
    public Result<AttendanceDetailDTO> getAttendanceDetail(@PathVariable Long taskId) {
        AttendanceDetailDTO detail = attendanceTaskService.getAttendanceDetail(taskId);
        return Result.success(detail);
    }
    
    /**
     * 修改学生签到状态
     */
    @PutMapping("/attendance/status")
    public Result<Void> updateAttendanceStatus(@Validated @RequestBody UpdateAttendanceStatusDTO dto) {
        Long teacherId = UserContext.getUserId();
        attendanceTaskService.updateAttendanceStatus(teacherId, dto);
        return Result.success();
    }
    
    /**
     * 导出签到详情Excel
     */
    @GetMapping("/attendance/task/{taskId}/export")
    public void exportAttendanceDetail(@PathVariable Long taskId, HttpServletResponse response) {
        log.info("开始导出签到任务{}的详情", taskId);
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("签到详情", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            
            // 获取Excel文件字节数组
            byte[] bytes = attendanceTaskService.exportAttendanceDetail(taskId);
            log.info("成功生成Excel文件，大小：{}字节", bytes.length);
            
            // 输出Excel文件
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
            log.info("Excel文件导出完成");
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            throw new BusinessException("导出Excel失败");
        }
    }
} 